//
//  UserAccount.swift
//  SinaWebo
//
//  Created by mis on 16/3/18.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit

class UserAccount: UIResponder, NSCoding {
    // 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    // 	access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expirces_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    // 过期时间
    var expirces_date: NSDate?
    // 当前授权用户的UID
    var uid: String?
    
    // 头像地址
    var avatar_large: String?
    // 用户名
    var name: String?
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override var description: String {
        let keys = ["access_token","expires_in","uid","avatar_large","name","expirces_date"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    // 解归档 class表示类方法
    class func loadAccount() -> UserAccount? {
        let patch = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(patch) as? UserAccount {
            return account
        }
        return nil
    }
    
    // 归档
    func saveAccount() {
        let patch = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        print(patch)
        NSKeyedArchiver.archiveRootObject(self, toFile: patch)
    }
    
    // 将自定义类数据 持久化
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        expirces_date = aDecoder.decodeObjectForKey("expirces_date") as? NSDate
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expirces_date, forKey: "expirces_date")
    }
}
